package com.company.tree;

import com.company.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author jrue
 * @version 1.0
 * @date 2020/1/27 21:06
 * https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
 * 给定一个二叉树，返回它的 前序 遍历。
 */
public class BinaryTreePreorderTraversal {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode thisNode = stack.pop();
            list.add(thisNode.val);
            if (thisNode.right != null) {
                stack.push(thisNode.right);
            }
            if (thisNode.left != null) {
                stack.push(thisNode.left);
            }
        }
        return list;
    }
}
